package com.ck.file.service.impl;

import com.ck.autoconfig.template.MinioTemplate;
import com.ck.file.service.FileService;
import com.ck.common.utils.file.FileUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.net.InetAddress;

/**
 * @author ck
 * @date 2023/8/24 18:06
 */
@Service

public abstract class MinioFileServiceImpl implements FileService {

    @Autowired
    MinioTemplate minioTemplate;

    @Value("${minio.bucketName}")
    private String bucketName;


    /**
     * minio文件上传
     * @param file
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile file, HttpServletRequest request) throws Exception {
        boolean exists = minioTemplate.bucketExists(bucketName);
        if (!exists){
            minioTemplate.createBucket(bucketName);
        }
        String fileName = FileUploadUtils.extractFilename(file);
        InputStream inputStream = file.getInputStream();
        String objectName=fileName;
        minioTemplate.putObject(bucketName,objectName,inputStream,"image/jpg");
        inputStream.close();
        String path = request.getScheme()+"://"+ InetAddress.getLocalHost().getHostAddress()+":"+request.getServerPort() +"/" + bucketName + "/" + objectName;
        return path;
    }
}
